package com.slipper.bpmn.dealer;

import com.slipper.constants.FlowConstants;
import com.slipper.groovy.util.MessageUtil;
import com.slipper.system.message.bo.MessageBO;
import com.slipper.util.Tool;
import org.springframework.beans.factory.InitializingBean;

import com.slipper.bpmn.vo.BpmnVO;
import com.slipper.system.flow.bo.FlowInstBO;
import com.slipper.system.flow.bo.FlowInstNodeBO;
import com.slipper.system.flow.bo.FlowNodeBO;

/**
 * 节点处理器
 */
public interface INodeDealer extends InitializingBean {
    /**
     * 此节点处理器处理的节点类型
     */
    String[] getTypes();

    /**
     * 节点处理，根据实际情况流转到下一节点
     * @param dealCnt 自动处理次数，0为开始
     * @param finished 是否完成
     * @param flowNode 当前节点
     * @param flowInst 流程实例数据
     * @param preInstNode 前一流程节点实例数据
     * @param currInstNode 当前流程实例数据
     * @param vo 当前表单数据
     */
    FlowInstNodeBO doDeal(
            int dealCnt,
            boolean finished,
            FlowNodeBO flowNode,
            FlowInstBO flowInst,
            FlowInstNodeBO preInstNode,
            FlowInstNodeBO currInstNode,
            BpmnVO vo);

    default void checkDealCntAssert(int dealCnt) {
        if (dealCnt >= 50) {
            throw new RuntimeException("流程自动处理节点次数过多！");
        }
    }

    default void sendMessage(FlowNodeBO flowNode, FlowInstBO flowInst, String receiverId) {
        String messageType = flowNode.getMessageType();
        if (Tool.isBlank(messageType)) return;

        String messageTpl = flowNode.getMessageTpl();
        if (Tool.isBlank(messageTpl)) return;

        String message = messageTpl;
        message = message.replaceAll("\\{\\{标题}}", flowInst.getTitle());

        String[] types = messageType.split(",");
        for (String type : types) {
            if (FlowConstants.FlowNode.MESSAGE_TYPE_INNER.equals(type)) {
                MessageUtil.send(
                        MessageBO.TYPE_MESSAGE,
                        null,
                        MessageBO.RECEIVE_TYPE_PART,
                        receiverId,
                        "待办消息",
                        message);
            }
        }
    }
    
    @Override
    default void afterPropertiesSet() {
        NodeDealerFactory.register(this.getTypes(), this);
    }
}
